﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using BL.Client.BudgetReportBL;
using Common.IO.FileIO;
using Common.ClassLib;

namespace UI.BudgetReport
{
    public partial class BRMain : Form
    {
        #region BRMain WinForm
        public BRMain()
        {
            InitializeComponent();
        }
        Form ParentForm;
        BudgetReportServerice BRS;
        
        public BRMain(Form parent, BudgetReportServerice brs)
        {
            this.InitializeComponent();
            this.ParentForm = parent;
            this.BRS = brs;
        }
        private void BRMain_Load(object sender, EventArgs e)
        {
            InitUserInfoPanel();
            InitFunction();
        }
        private void BRMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.BRS.UserLogOut();
            this.ParentForm.Close();
        }

        #endregion

        #region ReportWithExcel

        private void 从Excel文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ofdExcelFile.DefaultExt = ".xls";
            ofdExcelFile.Filter = "Excel文件(*.xls)|*.xls";
            ofdExcelFile.CheckFileExists = true;
            ofdExcelFile.FileName = "";
            ofdExcelFile.ShowDialog();
        }

        private void ofdExcelFile_FileOk(object sender, CancelEventArgs e)
        {
            DefinePanel(false, true, false);

            string excelfielpath = ofdExcelFile.FileName;
            tbExcelFilePath.Text = excelfielpath;
            ExcelIO excel = new ExcelIO(excelfielpath);
            dgvExcelData.DataSource = excel.GetData().Tables[0];

        }

        #endregion

        #region ReportBudget

        private void 直接上报ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefinePanel(true, false, false);

        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btReport_Click(object sender, EventArgs e)
        {
            OperateResult result = this.BRS.BudgetReport((DataTable)dgvExcelData.DataSource);
            if (result == OperateResult.Success)
                MessageBox.Show("上报成功！");
            else if (result == OperateResult.Fail)
                MessageBox.Show("上报失败！");
            else if (result == OperateResult.DisConnect)
                MessageBox.Show("操作失败，请检查服务器连接！");
        }

        
       
        private void BtnReport_Click(object sender, EventArgs e)
        {
            string budget_name = tbBudgetName.Text.Trim();
            string budget_price = nudBudgetPrice.Value.ToString().Trim();
            string pay_method_id = ((ComboBoxItem)(cbPayMethod.SelectedItem)).Value;
            string budget_remark = tbBudgetRemark.Text;
            string budget_type_id, budget_type_name;
            if (budget_name == "" || budget_price == "0" || cbBudgetMainType.SelectedItem == null)
            {
                MessageBox.Show("请完整填写信息！");
            }
            else
            {
                budget_type_id = ((ComboBoxItem)cbBudgetSubType.SelectedItem).Value;
                budget_type_name = ((ComboBoxItem)cbBudgetSubType.SelectedItem).Text.Trim();
               
                string infos = "您要上报的预算为：\n" +
                        "\n预算类别：  " + budget_type_name +
                "\n预算名称：   " + budget_name +
                "\n预算金额：   " + budget_price + "元" +
                "\n预算备注：   " + budget_remark +
                "\n\n\n请确认此信息无误后，点击\"确认\"上报预算， "+
                "\n如果需要修改请点\"取消\"返回修改";

                
                //if((MessageBox.Show(infos, "预算上报信息确认", MessageBoxButtons.OKCancel))
                //    == DialogResult.OK)
                //{
                //    OperateResult result = this.BRS.BudgetReport(
                //                budget_name, budget_price, pay_method_id,
                //                budget_type_id, budget_remark);
                //    if (result == OperateResult.Success)
                //    {
                //        ResetPanel(plReportBudget);
                //        MessageBox.Show("上报成功！");
                //    }
                //    else if (result == OperateResult.Fail)
                //        MessageBox.Show("上报失败！");
                //    else if (result == OperateResult.DisConnect)
                //        MessageBox.Show("操作失败，请检查服务器连接！");
                //}
            }
        }

        private void cbBudgetMainType1_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbBudgetSubType.Items.Clear();
            cbBudgetSubType.Text = "请选择";
            string budget_type_parentid = ((ComboBoxItem)cbBudgetMainType.SelectedItem).Value;
            DataSet ds = this.BRS.GetBudgetSubType(budget_type_parentid);
            if (ds == null)
            {
                MessageBox.Show("请检查网络连接！");
                return;
            }
            else
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    cbBudgetSubType.Items.Add(
                        new ComboBoxItem(dr["budget_type_name"].ToString(),
                        dr["budget_type_id"].ToString()));
                }
            }
        }

        #endregion

        #region BudgetCheck
        private void 查询尚未审批预算清单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.DefinePanel(false, false, true);
            this.InitDGVColumns();
            DataSet ds = this.BRS.GetBudgetInfoByState(((int)BUDGETSTATEID.UnChecked).ToString());
            if (ds == null)
                MessageBox.Show("请检查网络连接");
            else if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                MessageBox.Show("没有查询到数据！");
            else
                dgvBudgetCheck.DataSource = ds.Tables[0];

        }

        private void 已通过审批的ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefinePanel(false, false, true);
            this.InitDGVColumns();
            DataSet ds = this.BRS.GetBudgetInfoByState(((int)BUDGETSTATEID.Approved).ToString());
            if (ds == null)
                MessageBox.Show("请检查网络连接");
            else if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                MessageBox.Show("没有查询到数据！");
            else
                dgvBudgetCheck.DataSource = ds.Tables[0];
        }

        private void 未通过审批的ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefinePanel(false, false, true);
            this.InitDGVColumns();
            DataGridViewButtonColumn refillbutton = new DataGridViewButtonColumn();
            refillbutton.Name = "ReFillButton";
            refillbutton.UseColumnTextForButtonValue = true;
            refillbutton.Text = "重新修改上报";
            refillbutton.HeaderText = "操作";
            dgvBudgetCheck.Columns.Add(refillbutton);


            DataSet ds = this.BRS.GetBudgetInfoByState(((int)BUDGETSTATEID.Rejected).ToString());
            if (ds == null)
                MessageBox.Show("请检查网络连接");
            else if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                MessageBox.Show("没有查询到数据！");
            else
                dgvBudgetCheck.DataSource = ds.Tables[0];

        }

        private void 查询本部门已报销的预算清单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DefinePanel(false, false, true);
            this.InitDGVColumns();
            DataSet ds = this.BRS.GetBudgetInfoByState(((int)BUDGETSTATEID.Payed).ToString());
            if (ds == null)
                MessageBox.Show("请检查网络连接");
            else if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                MessageBox.Show("没有查询到数据！");
            else
                dgvBudgetCheck.DataSource = ds.Tables[0];

        }

        #endregion

        #region InitPanel
        private void InitFunction()
        {
            InitReportBudgetFunction();
            InitReportBudgetWithExcelFunction();
            InitBudgetCheck();
            DefinePanel(true, false, false);
        }

        private void InitUserInfoPanel()
        {
            string department_name = this.BRS.GetDepartmentName();
            string user_name = this.BRS.GetUserName();
            if (department_name != null && user_name != null)
            {
                lbDepartmentName.Text = department_name;
                lbUserName.Text = user_name;
            }
            else
                MessageBox.Show("请检查网络连接！");


        }
        private void InitReportBudgetFunction()
        {
            plReportBudget.Dock = DockStyle.Fill;

            cbBudgetMainType.Items.Clear();
            cbBudgetMainType.Text = "请选择";
            DataSet ds = this.BRS.GetBudgetType();
            if (ds == null)
            {
                MessageBox.Show("请检查网络连接！");
                return;
            }
            else
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    cbBudgetMainType.Items.Add(
                        new ComboBoxItem(dr["budget_type_name"].ToString(),
                        dr["budget_type_id"].ToString()));
                }
            }

            cbPayMethod.Items.Clear();
            cbPayMethod.Text = "请选择";
            ds = this.BRS.GetPayMethod();
            if (ds == null)
            {
                MessageBox.Show("请检查网络连接！");
                return;
            }
            else
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    cbPayMethod.Items.Add(
                        new ComboBoxItem(dr["pay_method_name"].ToString(),
                        dr["pay_method_id"].ToString()));
                }
            }
        }

        private void InitBudgetCheck()
        {
            plBudgetCheck.Dock = DockStyle.Fill;
            this.InitDGVColumns();
        }

        private void InitDGVColumns()
        {
            dgvBudgetCheck.AllowUserToAddRows = false;
            dgvBudgetCheck.Dock = DockStyle.Fill;
            dgvBudgetCheck.Columns.Clear();
            dgvBudgetCheck.AutoGenerateColumns = false;
            string[] headertext = { "预算编号", "预算类别", "预算名称", 
                "预算总金额(元)","预算余额(元)", "开支方式","预算备注", "上报部门", 
                "上报人", "上报时间", "审核时间", 
                "状态" };
            string[] columnname = {"BudgetId","BudgetTypeName","BudgetName",
                "BudgetPrice", "BudgetBalance", "PayMethodName","BudgetRemark","DepartmentName",
                 "UserRealName","BudgetReportDatetime","BudgetCheckDatetime",
                 "BudgetStateName", };
            string[] datapropertyname = {"budget_id","budget_type_name","budget_name",
                "budget_price", "budget_balance", "pay_method_name", "budget_remark",
                "department_name","user_realname", "budget_report_datetime", "budget_check_datetime",
                "budget_state_name"};
            for (int i = 0; i < headertext.Length; i++)
            {
                DataGridViewTextBoxColumn newcolumn = new DataGridViewTextBoxColumn();
                newcolumn.Name = columnname[i];
                newcolumn.DataPropertyName = datapropertyname[i];
                newcolumn.HeaderText = headertext[i];
                newcolumn.ReadOnly = true;
                newcolumn.SortMode = DataGridViewColumnSortMode.Automatic;
                newcolumn.Resizable = DataGridViewTriState.False;
                dgvBudgetCheck.Columns.Add(newcolumn);
            }
            dgvBudgetCheck.CellContentClick += new DataGridViewCellEventHandler(dgvBudgetCheck_CellContentClick);
        }

        private void dgvBudgetCheck_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBudgetCheck.Columns["ReFillButton"] != null)
            {
                if (e.ColumnIndex.Equals(this.dgvBudgetCheck.Columns["ReFillButton"].Index))
                {
                    DefinePanel(true, false, false);
                    tbBudgetName.Text = 
                        this.dgvBudgetCheck.Rows[e.RowIndex].Cells["BudgetName"].Value.ToString().Trim();
                    tbBudgetRemark.Text = 
                        this.dgvBudgetCheck.Rows[e.RowIndex].Cells["BudgetRemark"].Value.ToString().Trim();
                    nudBudgetPrice.Value =
                        (int)(this.dgvBudgetCheck.Rows[e.RowIndex].Cells["BudgetPrice"].Value);

                    string budget_type = 
                        this.dgvBudgetCheck.Rows[e.RowIndex].Cells["BudgetTypeName"].Value.ToString().Trim();
                    if (cbBudgetMainType.FindString(budget_type) != -1)
                    {
                        cbBudgetMainType.SelectedIndex = cbBudgetMainType.FindString(budget_type);
                    }
                    else
                    {
                        cbBudgetSubType.SelectedIndex = cbBudgetSubType.FindString(budget_type);
                     //   cbBudgetMainType.SelectedIndex = Convert.ToInt32(((ComboBoxItem)(cbBudgetSubType.SelectedItem)).Value);
                    }
                }
            }
        }

        private void InitReportBudgetWithExcelFunction()
        {
            plReportWithExcel.Dock = DockStyle.Fill;
        }
        #endregion

        #region PanelControl
        private void DefinePanel(bool rb, bool rwe, bool bc)
        {
            plReportBudget.Visible = rb;
            plReportWithExcel.Visible = rwe;
            plBudgetCheck.Visible = bc;
        }

        private void ResetPanel(Panel pl)
        {
            foreach (Control ctrl in pl.Controls)
            {
                if (ctrl.GetType() == typeof(ComboBox))
                {
                    ((ComboBox)ctrl).Text = "请选择";
                }
                else if(ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)ctrl).Text = "";
                }
                nudBudgetPrice.Value = 0;
            }
        }
        #endregion

        private void 查询本日上报预算清单ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        
        

        






    }
}
